package com.sticktogether;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Vibrator;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.preference.RingtonePreference;
import android.text.TextUtils;

import com.sticktogether.photoreceiver.PhotoDatabase;
import com.sticktogether.pushnotifications.GCMIntentService;
import com.sticktogether.server.ServerCommunication;
import com.sticktogether.services.GpsService;

@SuppressWarnings("deprecation")
public class SettingsActivity extends PreferenceActivity {
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		addPreferencesFromResource(R.xml.preferences);
		// Bind the summaries of EditText/List/Dialog/Ringtone preferences to
		// their values. When their values change, their summaries are updated
		bindPreferenceSummaryToValue(findPreference("sync_frequency"));
		bindPreferenceSummaryToValue(findPreference("track_frequency"));
		bindPreferenceSummaryToValue(findPreference("track_frequency"));
		bindPreferenceSummaryToValue(findPreference("notifications_new_message_ringtone"));
		bindPreferenceSummaryToValue(findPreference("vibrate_pattern"));
		bindPreferenceSummaryToValue(findPreference("zoomspeed"));
		bindPreferenceSummaryToValue(findPreference("zoomlevel"));
		bindPreferenceSummaryToValue(findPreference("led_color"));
		findPreference("tracking_enable").setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);
		findPreference("auto_upload_enable").setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);
		findPreference("gps_mode").setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);
		findPreference("logout").setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
			
			public boolean onPreferenceClick(Preference arg0) {
				ServerCommunication.logout();
				return false;
			}
		});
		
		
	}
	
	


	/**
	 * This method is called when a preference is changed.
	 */
	private Preference.OnPreferenceChangeListener sBindPreferenceSummaryToValueListener = new Preference.OnPreferenceChangeListener() {
		
		public boolean onPreferenceChange(Preference preference, Object value) {
			String stringValue = value.toString();
			updateSummary(preference, stringValue);
			
			// The user has changed the vibrate patter, so vibrate once in the new vibrate pattern.
			if (preference instanceof ListPreference) {
				ListPreference listPreference = (ListPreference) preference;
				if(listPreference.getKey().equals("vibrate_pattern")) {
					Vibrator v = (Vibrator) preference.getContext().getSystemService(Context.VIBRATOR_SERVICE);
					long[] vibratePattern = GCMIntentService.getVibratePattern(Integer.parseInt(value.toString()));
					v.vibrate(vibratePattern, -1);
				}
			} 
			
			// tracking state was changed
			if(preference.getKey().equals("tracking_enable")) {
				if(((Boolean) value)) {
			    	// Start the GPS service.
					Intent Serviceintent = new Intent(preference.getContext(), GpsService.class);
					preference.getContext().startService(Serviceintent);
				}
				else {
					// Stop the GPS service
					Intent Serviceintent = new Intent(preference.getContext(), GpsService.class);
					preference.getContext().stopService(Serviceintent);
				}
					
			}
			
			else if(preference.getKey().equals("auto_upload_enable")) { 
		    	if(!((Boolean) value)) {
		    		// auto upload has been disabled
		    		// clean up the database
		    		PhotoDatabase photos = new PhotoDatabase(preference.getContext());
		    		SQLiteDatabase db = photos.getWritableDatabase();
		    		db.delete("photos", null, null);
		    		db.close();
		    	}
			}
	    	
			
			// update the minDistance, minTime of the GPS service by restarting it.
			else if(preference.getKey().equals("track_frequency") || preference.getKey().equals("sync_frequency") || preference.getKey().equals("gps_mode")) {
				Intent Serviceintent = new Intent(preference.getContext(), GpsService.class);
				preference.getContext().startService(Serviceintent);
				if(preference.getKey().equals("gps_mode")) {
					if(((Boolean) value)) {
						AlertDialog alertDialog = new AlertDialog.Builder(preference.getContext()).create();
				        // Setting Dialog Title
				        alertDialog.setTitle(preference.getContext().getString(R.string.gps_mode));
				        // Setting Dialog Message
				        alertDialog.setMessage(preference.getContext().getString(R.string.gps_mode_explan));
				        // Setting Icon to Dialog
				        alertDialog.setIcon(R.drawable.ic_launcher);
				        // Setting OK Button
				        alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, preference.getContext().getString(R.string.ok), new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int which) {}
						});
				        // Showing Alert Message
				        alertDialog.show();
					}
				}
				else if(preference.getKey().equals("sync_frequency") && Integer.parseInt(stringValue)==3600000) {
					AlertDialog alertDialog = new AlertDialog.Builder(preference.getContext()).create();
			        // Setting Dialog Title
			        // alertDialog.setTitle(preference.getContext().getString(R.string.gps_mode));
			        // Setting Dialog Message
			        alertDialog.setMessage(preference.getContext().getString(R.string.sync_frequency_explain));
			        // Setting Icon to Dialog
			        alertDialog.setIcon(R.drawable.ic_launcher);
			        // Setting OK Button
			        alertDialog.setButton(DialogInterface.BUTTON_POSITIVE, preference.getContext().getString(R.string.ok), new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int which) {}
					});
			        // Showing Alert Message
			        alertDialog.show();
				}
			}
		
			return true;
		}
	};

	/**
	 * Binds a preference's summary to its value. More specifically, when the
	 * preference's value is changed, its summary (line of text below the
	 * preference title) is updated to reflect the value. The summary is also
	 * immediately updated upon calling this method. The exact display format is
	 * dependent on the type of preference.
	 * 
	 * @see #sBindPreferenceSummaryToValueListener
	 */
	private void bindPreferenceSummaryToValue(Preference preference) {
		
		// Set the listener to watch for value changes.
		preference.setOnPreferenceChangeListener(sBindPreferenceSummaryToValueListener);

		// update summary immediately with the preference's current value.
		updateSummary( preference, PreferenceManager.getDefaultSharedPreferences(preference.getContext()).getString(preference.getKey(), ""));
	}
	
	/**
	 * A method that updates the preference's summary  to reflect its value.
	 */
	private void updateSummary(Preference preference, String stringValue) {
		if (preference instanceof ListPreference) {
			
			// For list preferences, look up the correct display value in
			// the preference's 'entries' list.
			ListPreference listPreference = (ListPreference) preference;
			int index = listPreference.findIndexOfValue(stringValue);

			// Set the summary to reflect the new value.
			preference.setSummary(index >= 0 ? listPreference.getEntries()[index] : null);
			
			if(preference.getKey().equals("sync_frequency")) {
				if(Integer.parseInt(stringValue)==3600000) {
					findPreference("track_frequency").setEnabled(false);
				}
				else {
					findPreference("track_frequency").setEnabled(true);
				}
			}

		} else if (preference instanceof RingtonePreference) {
			// For ringtone preferences, look up the correct display value
			// using RingtoneManager.
			if (TextUtils.isEmpty(stringValue)) {
				// Empty values correspond to 'silent' (no ringtone).
				preference.setSummary(R.string.pref_ringtone_silent);

			} else {
				Ringtone ringtone = RingtoneManager.getRingtone(
						preference.getContext(), Uri.parse(stringValue));

				if (ringtone == null) {
					// Clear the summary if there was a lookup error.
					preference.setSummary(null);
				} else {
					// Set the summary to reflect the new ringtone display
					// name.
					String name = ringtone
							.getTitle(preference.getContext());
					preference.setSummary(name);
				}
			}

		} else {
			// For all other preferences, set the summary to the value's
			// simple string representation.
			// preference.setSummary(stringValue);
		}
	}
	
	
}
